<template>
  <div>
    <el-form label-width="80px" :inline="true">
      <el-form-item label="学校名称">
        <el-input
          v-model="search.name"
          placeholder="请输入学校名称"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button type="primary" @click="onBatchLaunch"
          >批量上线launch</el-button
        >
        <el-button type="primary" @click="onBatchApp">批量上线app</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="schoolList"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="学校名称">
        <template slot-scope="scope">
          <router-link :to="`/launch-school-detail?id=${scope.row.id}`">{{
            scope.row.schoolName
          }}</router-link>
        </template>
      </el-table-column>
      <el-table-column label="覆盖年级">
        <template slot-scope="scope">
          <span>{{ scope.row.grade }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属地区">
        <template slot-scope="scope">
          <span>{{
            `${scope.row.provinceName}${scope.row.cityName}${scope.row.areaName}`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="APP数量">
        <template slot-scope="scope">
          <span>{{ scope.row.appCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="onlineLaunch(scope.row, 'onlineLaunchVisible')"
            >上线launch</el-button
          >
          <el-button
            size="mini"
            @click="onlineLaunch(scope.row, 'onlineAppVisible')"
            >上线app</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="Number(pagination.total)"
    >
    </el-pagination>
    <el-dialog title="批量上线Launch" :visible.sync="onlineBatchVisible">
      <el-radio-group
        v-model="launchType"
        @change="getLaunchList"
        size="medium"
      >
        <el-radio-button label="2">教师</el-radio-button>
        <el-radio-button label="1">学生</el-radio-button>
      </el-radio-group>
      <div style="margin-top: 10px">
        <span>选中学校：</span>
        <el-tag
          style="margin-right: 5px"
          v-for="tag in multipleSelection"
          :key="tag.id"
        >
          {{ tag.schoolName }}
        </el-tag>
      </div>
      <div
        style="padding-top: 10px;marginTop: 10px;border-top: 1px solid #eaeaea"
      >
        <p>选择版本：</p>
        <el-radio-group v-model="selectBatchLaunch">
          <el-radio
            v-for="launch in batchLaunchList"
            :key="launch.id"
            :label="launch.id"
            >{{
              `${launch.version}（${
                launchType == 1
                  ? `${launch.gradeCount}个年级、${launch.classesCount}个班级`
                  : `${launch.teacherCount}个教师`
              }）`
            }}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
              launch.remark
            }}</el-radio
          >
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onlineBatchVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchOnlineLaunch">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="批量上线App" :visible.sync="onlineBatchAppVisible">
      <el-radio-group v-model="launchType" @change="getAppList" size="medium">
        <el-radio-button label="2">教师</el-radio-button>
        <el-radio-button label="1">学生</el-radio-button>
      </el-radio-group>
      <div style="margin-top: 10px">
        <span>选中学校：</span>
        <el-tag
          style="margin-right: 5px"
          v-for="tag in multipleSelection"
          :key="tag.id"
        >
          {{ tag.schoolName }}
        </el-tag>
      </div>
      <div
        style="padding-top: 10px;marginTop: 10px;border-top: 1px solid #eaeaea"
      >
        <p>选择版本：</p>
        <el-tabs
          v-model="activeName"
          tab-position="left"
          style="height: 200px;"
          @tab-click="handleClick"
        >
          <el-tab-pane :name="app.id + ''" v-for="app in appList" :key="app.id"
            ><span slot="label"
              ><el-checkbox v-model="app.checked" /> {{ app.name }}</span
            >
            <el-radio-group v-model="app.selectBatchLaunch">
              <el-radio
                v-for="version in app.versionList"
                :key="version.appVersionId"
                :label="version.appVersionId"
                >{{
                  `${version.version}（${
                    launchType == 1
                      ? `${version.gradeCount}个年级、${version.classesCount}个班级`
                      : `${version.teacherCount}个教师`
                  }）`
                }}<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{
                  version.remark
                }}</el-radio
              >
            </el-radio-group>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onlineBatchVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchOnlineApp">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="上线launch" :visible.sync="onlineLaunchVisible">
      <school-online-launch
        :showTypeSelect="true"
        :schoolId="selectSchool"
        @cancel="selectCancel"
        @change="selectChange"
      ></school-online-launch>
    </el-dialog>
    <el-dialog title="上线app" width="860px" :visible.sync="onlineAppVisible">
      <school-online-app
        :showTypeSelect="true"
        :schoolId="selectSchool"
        @cancel="selectCancel"
        @change="selectAppChange"
      ></school-online-app>
    </el-dialog>
  </div>
</template>

<script>
// import base from '@/views/base.vue'
import {
  queyEnumByTableName,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api.js'
import { querySchool } from '@/api/user'
import {
  getSchoolManageList,
  batchOnlineLaunch,
  batchOnlineApp,
  schoolLaunchList,
  getAppList,
  schoolAppList,
  onlineLaunch,
  onlineApp
} from '@/api/launch'
import {
  adminschoollist,
  enumschoolall,
  adminimportschoolExport
} from '@/api/lcmapi.js'
import SchoolOnlineLaunch from './components/school-online-launch.vue'
import SchoolOnlineApp from './components/school-online-app.vue'
export default {
  name: 'launch-school',
  // extends: base,
  data () {
    return {
      selectSchool: null,
      onlineLaunchVisible: false,
      onlineAppVisible: false,
      activeName: '',
      launchType: 2,
      onlineBatchVisible: false,
      onlineBatchAppVisible: false,
      search: {
        name: ''
      },
      value: true,
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      schoolList: [],
      multipleSelection: [],
      batchLaunchList: [],
      selectBatchLaunch: null,
      appList: []
    }
  },
  components: {
    SchoolOnlineLaunch,
    SchoolOnlineApp
  },
  activated () {
    this.$store.dispatch('common/saveRegion')
    // this.getDataList("", "", "", "");
    this.queyEnumByTableName()
  },
  computed: {},
  async created () {
    this.getSchoolManageList()
    // this.getLaunchList()
    // this.getAppList()
  },
  methods: {
    onlineLaunch (record, name) {
      this.selectSchool = record.id
      this[name] = true
    },
    async selectAppChange (val) {
      let classList = []
      if (val.launchType == 1) {
        for (let i = 0; i < val.gradeList.length; i++) {
          const res = val.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: val.schoolId
            })
          }
        }
      } else {
        for (let i = 0; i < val.teacherList.checkedData.length; i++) {
          const classId = val.teacherList.checkedData[i]
          classList.push({
            teacherId: classId,
            schoolId: val.schoolId
          })
        }
      }
      let finialList = []
      val.appList.map(item => {
        if (item.selectBatchLaunch) {
          finialList.push({
            appVersionId: item.selectBatchLaunch,
            classesLists: classList
          })
        }
      })
      if (!classList.length) {
        this.$message.error('上线对象不能为空')
      } else {
        const updateRes = await onlineApp(finialList)
        if (updateRes[0]) {
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          await this.getSchoolManageList()
          this.onlineAppVisible = false
        }
      }
      console.log(val)
    },
    async selectChange (val) {
      if (!val.selectLaunch) {
        this.$message.error('版本不能为空')
        return
      }
      let classList = []
      if (val.launchType == 1) {
        for (let i = 0; i < val.gradeList.length; i++) {
          const res = val.gradeList[i]
          for (let c = 0; c < res.checkedData.length; c++) {
            const classId = res.checkedData[c]
            classList.push({
              classesId: classId,
              gradeId: res.gradeId,
              schoolId: val.schoolId
            })
          }
        }
      } else {
        for (let i = 0; i < val.teacherList.checkedData.length; i++) {
          const classId = val.teacherList.checkedData[i]
          classList.push({
            teacherId: classId,
            schoolId: val.schoolId
          })
        }
      }
      if (!classList.length) {
        this.$message.error('上线对象不能为空')
      } else {
        const updateRes = await onlineLaunch({
          classesLists: classList,
          launchId: val.selectLaunch
        })
        if (updateRes[0]) {
          this.$message.error(updateRes[1].message)
        } else {
          this.$message.success('上线成功')
          this.onlineLaunchVisible = false
        }
      }
      console.log(val)
    },
    selectCancel () {
      this.onlineLaunchVisible = false
      this.onlineAppVisible = false
    },
    async batchOnlineApp () {
      let schoolIds = []
      this.multipleSelection.map(item => schoolIds.push(item.id))
      let appVersionId = []
      this.appList.map(item => {
        if (item.selectBatchLaunch) appVersionId.push(item.selectBatchLaunch)
      })
      if (!appVersionId.length) {
        this.$message.error('版本不能为空')
      } else {
        const updateRes = await batchOnlineApp({ schoolIds, appVersionId })
        this.$message[updateRes[0] ? 'error' : 'success'](
          updateRes[0] ? '操作失败' : '操作成功'
        )
        this.onlineBatchAppVisible = false
      }
    },
    async batchOnlineLaunch () {
      if (!this.selectBatchLaunch) {
        this.$message.error('请先选择版本')
        return
      }
      let schoolIds = []
      this.multipleSelection.map(item => schoolIds.push(item.id))
      const res = await batchOnlineLaunch({
        schoolIds,
        launchId: this.selectBatchLaunch
      })
      this.$message[res[0] ? 'error' : 'success'](
        res[0] ? '操作失败' : '操作成功'
      )
      this.onlineBatchVisible = false
    },
    async handleClick (tab, event) {
      console.log(tab, event, this.activeName)
      this.getAppVersionList(this.activeName)
    },
    async getLaunchList () {
      this.selectBatchLaunch = null
      let schoolIds = []
      this.multipleSelection.map(item => schoolIds.push(item.id))
      console.log('schoolIds', schoolIds)
      const res = await schoolLaunchList({
        type: this.launchType,
        schoolIds: schoolIds.join(',')
      })
      this.batchLaunchList = res[1].data
    },
    async getAppList () {
      const res = await getAppList({
        type: this.launchType,
        pageSize: 999,
        page: 1
      })
      res[1].data.map(item => {
        item.versionList = []
        item.checked = false
        item.selectBatchLaunch = null
      })
      this.appList = res[1].data
      this.activeName = res[1].data[0].id + ''
      this.getAppVersionList(res[1].data[0].id)
    },
    async getAppVersionList (appId) {
      const _index = this.appList.findIndex(item => item.id == appId)
      if (!this.appList[_index].versionList.length) {
        let schoolIds = []
        this.multipleSelection.map(item => schoolIds.push(item.id))
        const versionList = await schoolAppList({
          appId,
          schoolIds: schoolIds.join(',')
        })
        this.$nextTick(() => {
          this.appList[_index].versionList = versionList[1].data
        })
      }
    },
    onBatchApp () {
      if (!this.multipleSelection.length) {
        this.$message.error('请先选择学校')
        return
      }
      this.getAppList()
      this.onlineBatchAppVisible = true
    },
    onBatchLaunch () {
      if (!this.multipleSelection.length) {
        this.$message.error('请先选择学校')
        return
      }
      this.getLaunchList()
      this.onlineBatchVisible = true
    },
    handleSelectionChange (val) {
      console.log('val', val)
      this.multipleSelection = val
    },
    async getSchoolManageList () {
      const res = await getSchoolManageList({
        page: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        schoolName: this.search.name
      })
      console.log('schoolList', res)
      this.schoolList = res[1].data
      this.pagination.total = res[1].total
    },
    async onSubmit () {
      this.pagination.pageNum = 1
      await this.getSchoolManageList()
    },
    async handleCurrentChange (val) {
      this.pagination.pageNum = val
      await this.getSchoolManageList()
    },
    async handleSizeChange (val) {
      this.pagination.pageSize = val
      await this.getSchoolManageList()
    },
    // 获取枚举
    async queyEnumByTableName () {
      // 获取学校的枚举接口
      let selectArr = {
        schoolType: [], // 学校性质
        level: [], // 学校等级
        studentScale: [], // 学生规模
        isOpen: [], // 状态
        coverageGrade: [] // 覆盖年级
      }
      let enumschoolallRes = await enumschoolall({})
      if (enumschoolallRes[0]) {
        return
      }
      this.selectArr = enumschoolallRes[1].data
      this.selectArr.level = [
        {
          label: 'A',
          value: 1
        },
        {
          label: 'B',
          value: 2
        },
        {
          label: 'C',
          value: 3
        }
      ]
      this.selectArr.coverageGrade = [
        {
          label: '幼儿园',
          value: 1
        },
        {
          label: '小学',
          value: 2
        },
        {
          label: '初中',
          value: 3
        },
        {
          label: '高中',
          value: 4
        }
      ]
    }
  }
}
</script>
<style scoped>
.el-dialog__body {
  padding-top: 5px !important;
}
.el-radio {
  display: block;
  margin-bottom: 15px;
}
.el-radio + .el-radio {
  margin-left: 0;
}
</style>
